// 引入微信的相关 API
const date = new Date();
const day = date.getDate(); //获取日期/
// const year = date.getFullYear(); //获取年份
const month = date.getMonth() + 1 //获取月份
var mon = month.toString().padStart(2, '0'); //月份转换两位字符
import * as echarts from '../../ec-canvas/echarts';
Page({
  data: {
    //需要修改的地方
    uid: "4892bd7fe005ecbbccf35929157ec7e7", //用户密钥，巴法云控制台获取
    Auto: "2DA984004", //并网控制器的主题
    Mppt: "5D9530006", //太阳能控制器的主题
    Shidian: "B6153B006", //市电的主题
    DaMen: "DC8324004", //大门控制器的主题
    ZYBeng: "4FDD72004", //增压泵控制器的主题
    Cdq: "0796AA004", //电动车充电器的主题
    Ktdy: "ktdy", //可调电源的主题
    Wlrg: "DD1EF8006", //可调电源的主题
    Name: ["Auto", "Mppt", "Shidian", "DaMen", "ZYBeng", "Cdq", "Ktdy", "Wlrg"],
    battryIMG: ["e.png", "e.png", "e.png", "e.png"], //单体电池图标
    echarts: false, //图表使能
    kaiguan: true, //开关刷新使能
    showModalStatus: false,
    auto: [],
    mppt: [],
    damen: [],
    zybeng: [],
    shidian: [],
    switchArray: [],
    sensorArray: [],
  },
  //屏幕打开时执行的函数
  onLoad: function () {
    // 将函数绑定到 ec 对象的 onInit 属性
    const ec = {
      onInit: this.initChart.bind(this)
    };
    this.setData({
      ec: ec
    });
    this.mina()
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.getcharts()
    wx.stopPullDownRefresh(); //停止下拉刷新
  },


  //发送数据
  LedSendMsg: function (topic, msg) {
    var that = this
    console.log(topic, msg)
    wx.request({
      url: 'https://api.bemfa.com/api/device/v1/data/1/push/get/?', //状态api接口，详见巴法云接入文档
      data: {
        uid: that.data.uid,
        topic: that.data[topic],
        msg: msg
      },
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      // success(res) {
      //   console.log(res.data)
      // }
    })
  },

  //开关按键更新
  switchArrData: function () {
    var that = this
    that.setData({
      sensorArray: []
    })
    that.setData({
      "sensorArray[0]": "0",
      "sensorArray[1]": that.data.mppt[20] == '1' ? true : false,
      "sensorArray[2]": that.data.mppt[21] == '1' ? true : false,
      "sensorArray[3]": that.data.damen[0] == 'on' ? true : false,
      "sensorArray[4]": that.data.shidian[0] == 'on' ? true : false,
      "sensorArray[5]": that.data.auto[9] == '1' ? true : false,
      "sensorArray[6]": that.data.auto[10] == '1' ? true : false,
      "sensorArray[7]": that.data.auto[11] == '1' ? true : false,
      "sensorArray[8]": that.data.auto[12] == '1' ? true : false,
      "sensorArray[9]": that.data.zybeng[4] == '1' ? true : false,
      "sensorArray[10]": that.data.zybeng[5] == '1' ? true : false,
      "sensorArray[11]": that.data.auto[15] == '1' ? true : false,
      "sensorArray[12]": that.data.auto[16] == '1' ? true : false,
    })
    for (let index = 1; index < that.data.sensorArray.length; index++) {
      if (that.data.sensorArray[index] === undefined) {
        // console.log("数据不全")
        // console.log(that.data.sensorArray)
        return
      }
      if (that.data.switchArray[index] != that.data.sensorArray[index]) {
        // console.log(that.data.switchArray)
        // console.log(that.data.sensorArray)
        that.setData({
          switchArray: []
        })
        that.setData({
          //数据险赋值异常使用方法
          switchArray: that.data.sensorArray.map(state => state),
        }, function () {
          // console.log("开关同步")
        })
        break
      }
    }
  },
  //主函数 
  mina: function () {
    const that = this;
    const totalTime = 2000;
    const topics = that.data.Name;
    let index = 0;
    let interval = 100;
    let onlineDeviceCount = 0;
    let isInitializing = false;
    let loop = () => {
      if (index >= topics.length) {
        // 处理完所有元素
        index = 0;
        if (!isInitializing) {
          that.getcharts(element);
        }
        isInitializing = true;
        interval = totalTime / onlineDeviceCount;
        onlineDeviceCount = 0;
        that.switchArrData();
      }
      // 生成设备标识名
      let element = topics[index++];
      // 生成设备在线名
      let deviceline = element + "_color";
      that.getline(element);
      // 检查设备状态数据是否存在，避免后续无效操作
      if (typeof that.data[deviceline] !== 'undefined' && that.data[deviceline] === true || !isInitializing) {
        onlineDeviceCount++;
        that.getShebei(element);
      } else {
        interval = 0;
      }
      // 延迟执行相关操作，间隔为设定的 interval
      let timer = setTimeout(() => {
        loop();
        clearTimeout(timer);
      }, interval);
    };
    // 首次调用循环函数
    loop();
  },

  //获取设备数据
  getShebei: function (e) {
    const that = this;
    const apiUrl = 'https://api.bemfa.com/api/device/v1/data/1/get';
    wx.request({
      url: apiUrl,
      data: {
        uid: that.data.uid,
        topic: that.data[e],
        num: 1
      },
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      success: (res) => {
        const data = res.data.msg;
        const name = e.toLowerCase();
        if (name.indexOf('wlrg') >= 0) {
          that.setData({
            [name]: data
          });
        } else if (data.substring(0, 9) == that.data[e]) {
          that.getShengji(data); //调用升级

        } else if (data.substring(0, 7) == "canshu#") {
          that.getCanshu(name, data); //调用参数

        } else if (data.substring(3, 4) == "-") {
          that.getTubiao(name, data); //调用图表

        } else if (data.substring(0, 3) == "on#" || data.substring(0, 4) == "off#") {
          that.getShuju(name, data); //调用数据

          if (that.data[e] == that.data.update) {
            that.setData({
              update: "",
            })
          }
        }
        // console.log(e, data);
      },
      fail: () => {
        console.log("无网络")
      }
    })
  },

  //请求设备状态
  getline: function (e) {
    var that = this
    //api 接口详细说明见巴法云接入文档
    wx.request({
      url: 'https://api.bemfa.com/api/device/v1/status/?', //状态api接口，详见巴法云接入文档
      data: {
        uid: that.data.uid,
        topic: that.data[e],
      },
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      success(res) {
        const onlineName = e + "_color"
        const online = res.data.status === "online"
        that.setData({
          [onlineName]: online
        })
        // console.log(that.data[onlineName]);
      }
    })
  },

  //解析图表数据
  getcharts: function (e) {
    var that = this
    that.LedSendMsg("Shidian", "charts" + mon)
    setTimeout(() => {
      that.LedSendMsg("Mppt", "charts" + mon)
    }, 2000);
  },

  //解析设备数据
  getShuju: function (name, data) {
    const that = this;
    const all_data_arr = data.split('#');
    that.setData({
      [name]: all_data_arr
    });
    if (name == "cdq") {
      const yAxis = "yAxis_" + name
      that.setData({
        [yAxis]: all_data_arr.slice(7, 18).map((item) => parseFloat(item))
      });
    }
    // console.log(name, that.data[name]);
  },

  //获取设备参数
  getCanshu: function (name, data) {
    const that = this;
    const all_data_arr = data.split('#');
    const canshu = "canshu_" + name + ""
    that.setData({
      [canshu]: all_data_arr
    });
    console.log(canshu, that.data[canshu]);
  },

  //获取设备图表
  getTubiao: function (name, data) {
    const that = this;
    const Array = []
    const yAxis = "yAxis_" + name + ""
    if (typeof that.data.yAxis_mppt === 'undefined' || typeof that.data.yAxis_shidian === 'undefined') {
      for (let i = 4; i - 1 <= day * 3; i += 3) {
        Array[(i - 4) / 3] = (data.slice(i, i + 3) / 100)
      }
      that.setData({
        [yAxis]: Array
      })
      // console.log(yAxis, that.data[yAxis])
    }
  },
  //升级按钮点击事件
  getShengji: function (e) {
    var that = this
    if (e.type == "longpress") {
      wx.showModal({
        title: '升级',
        content: e.target.dataset.name,
        success(res) {
          if (res.confirm) {
            that.LedSendMsg(e.target.dataset.shebei, "update")
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      const all_data_arr = e.split('#');
      that.setData({
        update: all_data_arr[0].toString(),
        process: all_data_arr[1],
      })
    }
  },


  //开关按钮点击事件
  changeSwitch: function (e) {
    var status = e.target.dataset.value + (e.detail.value == true ? "_on" : "_off")
    var that = this
    that.LedSendMsg(e.target.dataset.shebei, status)
  },

  //弹窗点击事件
  button_input: function (e) {
    // console.log(e)
    var that = this
    var button_input = e.type == "confirm"
    that.LedSendMsg(that.data.Shebei, e.target.dataset.value + (button_input ? "=" + e.detail.value : ""))
    that.setData({ //数据赋值给变量
      shuru: "",
    })
  },

  //弹窗事件
  tanchuan: function (e) {
    var that = this
    if (!that.data.showModalStatus) {
      that.setData({
        Shebei: e.target.dataset.shebei,
        Shebeiname: e.target.dataset.name,
      })
      that.setData({
        [that.data.Shebei + "State"]: true
      })
      that.LedSendMsg(that.data.Shebei, "canshu")
    }
    that.util()
  },
  //弹窗动画事件
  util: function () {
    var that = this
    /* 动画部分 */
    // 第1步：创建动画实例  
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });
    // 第2步：这个动画实例赋给当前的动画实例 
    // that.animation = animation;
    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-90).step();
    // 第4步：导出动画对象赋给数据对象储存 
    that.setData({
      animationData: animation.export()
    })
    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function () {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      that.setData({
        animationData: animation
      })
    }.bind(that), 300)
    // 显示 
    if (that.data.showModalStatus) {
      setTimeout(function () {
        that.setData({
          showModalStatus: false,
          [that.data.Shebei + "State"]: false
        })
      }.bind(that), 200);
    } else {
      that.setData({
        showModalStatus: true
      });
    }
  },

  initChart: function (canvas, width, height, dpr) {
    var that = this
    let xAxis = Array.from({
      length: day
    }, (_, index) => index + 1);
    let chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    // canvas.setChart(chart);
    var option = {
      title: [{
          text: '合计:0 kw.h',
          textStyle: {
            color: '#666',
            fontSize: 10, // 字体大小
            fontStyle: 'normal',
            fontWeight: 'normal'
          },
          padding: [40, 10] //---标题位置,因为图形是是放在一个dom中,因此用padding属性来定位
        },
        {
          text: '日期:0/0          电量:0 kw.h', //---副标题内容样式
          textStyle: {
            color: '#666',
            fontSize: 10, // 字体大小
            fontStyle: 'normal',
            fontWeight: 'normal'
          },
          padding: [40, 150] //---标题位置,因为图形是是放在一个dom中,因此用padding属性来定位
        }
      ],

      dataZoom: [{
        show: false, // 设置滚动条的隐藏与显示
        // startValue: xAxis.length - 15, // 展示后10个数据的索引
        type: "inside", // 在区域内控制拖动滚动条
      }, ],
      legend: {
        selectedMode: 'single',
        type: 'plain', //----图例类型，默认为'plain'，当图例很多时可使用'scroll'
      },
      series: [{
        name: '市电',
        type: 'bar',
        stack: 'Total',
      }, {
        name: '发电',
        type: 'bar',
        stack: 'Total',
      }, {
        name: '用电',
        type: 'bar',
        stack: 'Total',
      }, {
        name: '充电',
        type: 'bar',
        stack: 'Total',
      }],

      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: true, //设置为true
        // data: xAxis,
        axisLabel: {
          fontSize: 8, // 字体大小
          // formatter: '{value} 号'
        },
      },
      yAxis: {
        type: 'value',
        splitLine: { //---grid 区域中的分隔线
          show: true, //---是否显示，'category'类目轴不显示，此时我的y轴为类目轴，splitLine属性是有意义的
          lineStyle: {
            color: '#999',
            width: 1,
            type: 'dashed', //---类型
          },
        },
        splitArea: { //--网格区域
          show: false, //---是否显示，默认false
        },
        axisLabel: {
          fontSize: 8, // 字体大小
        },
      },
    };
    const abc = () => {
      chart.setOption({
        xAxis: {
          data: xAxis,
        },
        series: [{
            data: that.data.yAxis_shidian,
          },
          {
            data: that.data.yAxis_mppt,
          },
          {
            data: that.data.yAxis_auto,
          },
          {
            data: that.data.yAxis_cdq,
          },
        ],

      })
    }
    chart.on('legendselectchanged', function (params) {
      var name = params.name;
      let sum = 0;
      abc()
      if (name == "市电" && that.data.yAxis_shidian) {
        that.data.yAxis_shidian.forEach(item => {
          sum += item
        })
      } else if (name == "发电" && that.data.yAxis_mppt) {
        that.data.yAxis_mppt.forEach(item => {
          sum += item
        })
      } else if (name == "用电" && that.data.yAxis_auto) {
        that.data.yAxis_auto.forEach(item => {
          sum += item
        })
      } else if (name == "充电" && that.data.yAxis_cdq) {
        that.data.yAxis_cdq.forEach(item => {
          sum += item
        })
        chart.setOption({
          xAxis: {
            data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
          },
        })
      }
      // console.log(that.data.yAxis_mppt)
      // console.log(that.data.yAxis_cdq)
      chart.setOption({
        title: [{
          text: '合计:' + sum.toFixed(2) + 'kw.h',
        }, ]
      })
    });

    chart.on('mouseover', function (params) { // 移入事件'mouseover' 点击事件'click'
      var name = params.seriesName;
      console.log(name)
      if (name == '充电') {
        chart.setOption({
          title: [{},
            {
              text: '                      电量:' + params.value + ' Ah', //---副标题内容样式        
              textStyle: {
                color: '#666',
                fontSize: 10, // 字体大小
                fontStyle: 'normal',
                fontWeight: 'normal'
              },
              padding: [40, 150] //---标题位置,因为图形是是放在一个dom中,因此用padding属性来定位
            }
          ],
        });
      } else {
        chart.setOption({
          title: [{},
            {
              text: '日期:' + month + '/' + params.name + '       电量:' + params.value + ' kw.h', //---副标题内容样式        
              textStyle: {
                color: '#666',
                fontSize: 10, // 字体大小
                fontStyle: 'normal',
                fontWeight: 'normal'
              },
              padding: [40, 150] //---标题位置,因为图形是是放在一个dom中,因此用padding属性来定位
            }
          ],
        });
      }
    })

    setTimeout(function () {
      abc()
    }, 5000);
    option && chart.setOption(option);
    return chart;
  }
})